package com.ly.hotel.view.setting;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.model.WeatherCity;
import com.ly.hotel.model.WeatherCounty;
import com.ly.hotel.model.WeatherProvince;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.view.dialog.CityDialog;
import com.ly.hotel.view.dialog.CountyDialog;
import com.ly.hotel.view.dialog.ProvinceDialog;
import com.ly.hotel.webagent.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class SystemSettingActivity extends Activity {

	private Button sysInfoBtn;
	private Button spaServerBtn;
	private Button fileBrowserBtn;
	private Button sendBroadcastBtn;
	private Button backBtn;
	private Button wifiSettingBtn;
	private Button areaSelectBtn;
	private Button homeSortBtn;
	private List<WeatherProvince> weatherAreas = new ArrayList<>();
	private MyApplication app;
	private Handler handler;
	
	private LinearLayout rightLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);
		app = (MyApplication) this.getApplication();
		initView();
	}

	private void initView() {
		Log.i("SystemSettingActivity","deviceInfo:"+ MyApplication.getDeviceInfo());

		rightLayout = findViewById(R.id.rightLayout);
		sysInfoBtn = findViewById(R.id.sysInfoBtn);
		spaServerBtn = findViewById(R.id.spaServerSetBtn);
		fileBrowserBtn = findViewById(R.id.fileBrowserBtn);
		sendBroadcastBtn = findViewById(R.id.sendBroadcastBtn);
		backBtn = findViewById(R.id.backBtn);
		wifiSettingBtn = findViewById(R.id.wifiSettingBtn);
		areaSelectBtn = findViewById(R.id.selectAreaBtn);
		homeSortBtn = findViewById(R.id.homeSortBtn);
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what){
					case 0:
						ToastUtil.showShortToast(SystemSettingActivity.this,"设置成功",2000);
						break;
					case 1:
						ToastUtil.showShortToast(SystemSettingActivity.this,"失败",2000);
						break;
				}
			}
		};
		
		sysInfoBtn.requestFocus();
		sysInfoBtn.performClick();

		rightLayout.removeAllViews();
		SysinfoLayout vl = new SysinfoLayout(SystemSettingActivity.this,
				MyApplication.getDeviceInfo());
		rightLayout.addView(vl);

		sysInfoBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				rightLayout.removeAllViews();
				SysinfoLayout vl = new SysinfoLayout(
						SystemSettingActivity.this,
						MyApplication.getDeviceInfo());
				rightLayout.addView(vl);
			}
		});

		spaServerBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				rightLayout.removeAllViews();
				SpaServerSettingLayout l = new SpaServerSettingLayout(SystemSettingActivity.this);
				rightLayout.addView(l);
			}
		});
		fileBrowserBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				Builder builder = new Builder(
						SystemSettingActivity.this);

				builder.setTitle(getString(R.string.PasswordTips));
				final EditText editText = new EditText(SystemSettingActivity.this);
				editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				editText.setLines(1);
				editText.addTextChangedListener(new TextWatcher() {
					@Override
					public void beforeTextChanged(CharSequence s, int start, int count, int after) {

					}

					@Override
					public void onTextChanged(CharSequence s, int start, int before, int count) {

					}

					@Override
					public void afterTextChanged(Editable s) {
						if (editText.getText().toString().trim().equals("1111")) {
							SystemSettingActivity.this.startActivity(new Intent(SystemSettingActivity.this,MyHome.class));
						}
					}
				});
				builder.setView(editText);

				builder.setPositiveButton(getString(R.string.yes), new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						if (editText.getText().toString().trim().equals("1111")) {
							
							SystemSettingActivity.this.startActivity(new Intent(SystemSettingActivity.this,MyHome.class));
						} else {
							Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_SHORT)
									.show();
						}
					}
				});
				builder.setNegativeButton(getString(R.string.no), new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {

					}
				});

				builder.create().show();
			}

		});

		sendBroadcastBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				rightLayout.removeAllViews();
				SendBroadcastLayout layout = new SendBroadcastLayout(SystemSettingActivity.this);
				rightLayout.addView(layout);
			}
		});
		
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		wifiSettingBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				rightLayout.removeAllViews();
				WifiLayout wl = new WifiLayout(SystemSettingActivity.this);
				rightLayout.addView(wl);
			}
		});

		areaSelectBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showAreaSelect();
			}
		});

		homeSortBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				rightLayout.removeAllViews();
				HomeSortLayout hsl = new HomeSortLayout(SystemSettingActivity.this);
				rightLayout.addView(hsl);
			}
		});
	}


	//解析全国数据选择区域
	private void showAreaSelect(){
		weatherAreas.clear();
		String sendRes = getJson(this,"china.json");
		try {
			JSONArray jArr = new JSONArray(sendRes);
			for (int i =0; i <jArr.length(); i++){
				JSONObject obj = jArr.getJSONObject(i);
				String parent2 = obj.getString("parent2");
				String parent1 = obj.getString("parent1");

				String name = obj.getString("name");
				String id = obj.getString("id");
				String nameEn = obj.getString("en");

				WeatherCounty weatherCounty = new WeatherCounty(id,name,nameEn);
				WeatherProvince wp = getPv(parent2);
				if (wp == null){
					wp = new WeatherProvince(parent2);
					WeatherCity wc = new WeatherCity(parent1);
					wc.setWeatherCounties(weatherCounty);
					wp.setWeatherCities(wc);
					weatherAreas.add(wp);
				}else{
					WeatherCity wc = getCity(parent1,wp);
					if(wc == null){
						wc = new WeatherCity(parent1);
						wp.setWeatherCities(wc);
					}
					wc.setWeatherCounties(weatherCounty);
				}
			}
			showProvDialog();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	//选择市级地区
	public void showProvDialog(){
		ProvinceDialog provinceDialog = new ProvinceDialog(this,R.style.introDialog,weatherAreas);
		provinceDialog.setCanceledOnTouchOutside(true);
		provinceDialog.show();
	}

	//选择市级地区
	public void showCityDialog(List<WeatherCity> weatherCities){
		CityDialog cityDialog = new CityDialog(this,R.style.introDialog,weatherCities);
		cityDialog.setCanceledOnTouchOutside(true);
		cityDialog.show();
	}

	//选择具体区域
	public void showCountyDialog(List<WeatherCounty> weatherCounties){
		CountyDialog countyDialog = new CountyDialog(this,R.style.introDialog,weatherCounties);
		countyDialog.setCanceledOnTouchOutside(true);
		countyDialog.show();
	}

	private WeatherProvince getPv(String name){
		for (WeatherProvince wp : weatherAreas){
			if (wp.getName().equals(name)){
				return wp;
			}
		}
		return null;
	}

	private WeatherCity getCity(String name,WeatherProvince wp){
		for (WeatherCity wc : wp.getWeatherCities()){
			if (wc.getName().equals(name)){
				return wc;
			}
		}
		return null;
	}

	public void setAreaMsg(WeatherCounty weatherCounty){
		app.areaId = weatherCounty.getId();
		app.areaName = weatherCounty.getName() + ";" + weatherCounty.getNameEn();
		setArea(app.areaId,weatherCounty.getName(),weatherCounty.getNameEn());
	}


	//存储地区
	private void setArea(final String id,final String name,final String nameEn){
		new Thread(new Runnable() {
			@Override
			public void run() {
				String URL = MyApplication.getHostResUrl() + "/api/dbfile-write.json";
				JsonObject areaObj = new JsonObject();
				String myName = name;
				try {
					myName = URLEncoder.encode(name,"utf-8");
				}catch (UnsupportedEncodingException e){
					e.printStackTrace();
				}
				areaObj.addProperty("id", id);
				areaObj.addProperty("name", myName);
				areaObj.addProperty("nameEn", nameEn);
				String request = "filename=WeatherArae&content=" + areaObj.toString();
				Log.i("httpGet", URL + "?" + request);
				String sendRes = HttpRequest.sendGet(URL, request);
				try {
					JSONObject jsobj = new JSONObject(sendRes);
					int code = jsobj.getInt("code");
					if (code == 200) {
						handler.sendEmptyMessage(0);
					}else{
						handler.sendEmptyMessage(1);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public static String getJson(Context context, String fileName) {
		StringBuilder stringBuilder = new StringBuilder();
		//获得assets资源管理器
		AssetManager assetManager = context.getAssets();
		//使用IO流读取json文件内容
		try {
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
					assetManager.open(fileName), "utf-8"));
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				stringBuilder.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return stringBuilder.toString();
	}
}
